<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 菜单与用户组关联模型
 * @author Administrator
 *
 */
class System_group_menu_model extends MY_Model
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 根据用户组id查询该用户组菜单
     * @param int $group_id 用户组id
     * @return array
     */
    public function get_group_menu_group_id($group_id)
    {
        if (!empty($group_id)) {
            $this->db->where('group_id', $group_id);//where
            $group_menu = $this->db->select("system_group_menu.menu_id")->from("system_group_menu")->get()->result_array();
            return $group_menu;
        } else {
            return null;
        }
    }


    /**
     * 根据用户组id获取用户菜单
     * @param int $group_id
     * @return array
     */
    public function get_user_menu_by_gid($group_id)
    {
        $group_menu = $this->db->select("sys_gm.menu_id AS id, sys_m.parent_id, sys_m.name, sys_m.icon_path, sys_m.skip_address, sys_m.sort, sys_m.type")
            ->from("system_group_menu AS sys_gm")
            ->join('system_menu AS sys_m', 'sys_m.id = sys_gm.menu_id', 'left')
            ->where(['group_id' => $group_id])
            ->order_by('sys_m.sort', 'ASC')
            ->get()->result_array();

        $first_lvl = []; // 父级菜单
        foreach ($group_menu AS $key => $item) {
            if($item['type'] == 1){
                $first_lvl[] = $item;
                unset($group_menu[$key]);
            }
        }
        foreach ($first_lvl AS $key => $fl){
            $first_lvl[$key]['children'] = null;
            foreach($group_menu AS $item){
                if($item['parent_id'] == $fl['id']){
                    $first_lvl[$key]['children'][] = $item;
                }
            }
        }
        return $first_lvl;
    }


    public function replace_system_group_menu($data)
    {
        if (!empty($data['group_id']) && !empty($data['menus'])) {
            $this->db->delete('system_group_menu', array('group_id' => $data['group_id']));
            foreach ($data['menus'] as $id) {
                $group_menu = array();
                $group_menu['group_id'] = $data['group_id'];
                $group_menu['menu_id'] = $id;
                $group_menu['create_time'] = time();
                $this->db->insert('system_group_menu', $group_menu);
            }
            return $this->success;
        } else {
            return $this->param_error;
        }
    }
}